package com.scau.os.course_manager;

import com.scau.os.course_manager.bean.DeviceAllocationTable;
import com.scau.os.deviceManagement.DeviceUse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class DeviceManager {

    private final HashMap<String, List<DeviceAllocationTable>>map=new HashMap<>();
    private final HashMap<String,List<String>>deviceTable=new HashMap<>();
    private final DeviceUse deviceUse=new DeviceUse();

    public DeviceManager() {
       init();
    }

    public  boolean apply(DeviceAllocationTable deviceAllocationTable){
        //寻找这一类型的设备是否有可用的设备
        Boolean flag=false;
        if(deviceTable.containsKey(deviceAllocationTable.peripheralName)){
            for (String s :
                    deviceTable.get(deviceAllocationTable.peripheralName)) {
                flag=deviceUse.allocatePeripheral(s,deviceAllocationTable.time,deviceAllocationTable.pcb);
                if(flag){
                    //找到了直接退出
                    break;
                }
            }
        }
        //没找到，自己维护一个阻塞队列
        if(!flag&&map.containsKey(deviceAllocationTable.peripheralName)){
            map.get(deviceAllocationTable.peripheralName).add(deviceAllocationTable);
        } else{
            //EventSystem.instance.SendEvent("RefreshPeripheral", deviceAllocationTable.peripheralName);
            System.out.println("成功分配"+deviceAllocationTable.peripheralName);
        }
        return flag;
    }
    public void checkPeripheralList(String peripheralName){
        if(map.containsKey(peripheralName)&&map.get(peripheralName).size()!=0){
            apply(map.get(peripheralName).get(0));
            map.get(peripheralName).remove(0);
        }
    }
    private void init(){
        map.put("A",new ArrayList<>());
        map.put("B",new ArrayList<>());
        map.put("C",new ArrayList<>());
        List<String>tmp=new ArrayList<>();
        tmp.add("A1");
        tmp.add("A2");
        deviceTable.put("A",tmp);
        tmp=new ArrayList<>();
        tmp.add("B1");
        tmp.add("B2");
        tmp.add("B3");
        deviceTable.put("B",tmp);
        tmp=new ArrayList<>();
        tmp.add("C1");
        tmp.add("C2");
        tmp.add("C3");
        deviceTable.put("C",tmp);
    }
}
